#include "snake.h"

Snake::Snake()
{

    snaky = new LinkedList();

    eat = false;
    move = 4;

    QTimer *m_timer = new QTimer( this );
    connect( m_timer, SIGNAL(timeout()), this, SLOT(update()) );
    m_timer->start( 160 ); // 32 fps

}


void Snake::initializeGL() {

    glShadeModel(GL_SMOOTH);         // Enables Smooth Shading
    glClearColor(0.0f, 0.6f, 1.0f, 1.0f);
    glClearDepth(1.0f);					// Depth Buffer Setup
    glEnable(GL_DEPTH_TEST);				// Enables Depth Testing
    glDepthFunc(GL_LEQUAL);				// The Type Of Depth Test To Do
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  // Really Nice Perspective Calculations
}

void Snake::resizeGL(int width, int height) {
    if (height == 0)	// Prevent A Divide By Zero By
    {
        height = 1;	// Making Height Equal One
    }
    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
    glLoadIdentity();            // Reset  The Projection Matrix

    // Calculate The Aspect Ratio Of The Window
    gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

    glMatrixMode(GL_MODELVIEW);		// Select The Modelview Matrix
    glLoadIdentity();
}


void Snake::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);			// Clear Screen And Depth Buffer
    glLoadIdentity();							// Reset The Current Matrix

    glTranslatef(0.0f,0.0f,-60.0f);                   // Left 1.5 Then Into Screen Six Units


    glColor3f(1.0f,0.0f,0.0f);

    glBegin(GL_QUADS);
        // Start Drawing Quads
        snaky->drawList();
    glEnd();                                                            // Done Drawing Quads
}

void Snake::update(){

    switch(move)
    {
    case 1:
        snaky->up(eat);
        break;

    case 2:
        snaky->right(eat);
        break;

    case 3:
        snaky->down(eat);
        break;

    case 4:
        snaky->left(eat);
        break;
    }


    updateGL();
}

void Snake::keyPressEvent(QKeyEvent *event){

    switch(event->key()){
    case Qt::Key_Up:
        if( move%2 == 0 )
            move = 1;
        break;
    case Qt::Key_Down:
        if( move%2 == 0)
            move = 3;
        break;
    case Qt::Key_Left:
        if( move%2 == 1)
            move = 4;
        break;
    case Qt::Key_Right:
        if( move%2 == 1)
            move = 2;
        break;
    case Qt::Key_B:
        if(eat)
            eat = false;
        else
            eat = true;
        break;
    case Qt::Key_F1:
        setWindowState(windowState() ^ Qt::WindowFullScreen); // Toggle fullscreen on F1
        break;
    case Qt::Key_Escape:
        close();
    }
}
